package cashpointer.core.dao;

import cashpointer.core.model.Owner;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * Klasa wspomagajaca operacje bazodanowe na tabeli Owner.
 * @author wojciech topolski
 * @version 2009-03-17
 */
public class OwnerDaoHibernate extends HibernateDaoSupport implements OwnerDao {
    /**
     * Funkcja dodaje nowego badz aktualizuje juz istniejacego wlasciciela.
     * @param owner Owner
     */
    public void save(Owner owner) {
        getHibernateTemplate().saveOrUpdate(owner);
    }

    /**
     * Funkcja usuwa wlasciciela bankomatu.
     * @param owner Owner
     */
    public void delete(Owner owner) {
        getHibernateTemplate().delete(owner);
    }

    /**
     * Funkcja pobiera wlasciciela bankomatu identyfikujac go za pomoca id.
     * @param id Long
     * @return Owner
     */
    public Owner getById(Long id) {
        return (Owner) getHibernateTemplate().get(Owner.class, id);
    }

    /**
     * Funkcja pobiera wlasciciela bankomatu identyfikujac go za pomoca nazwy.
     * @param id Long
     * @return Owner
     */
    public Owner getByName(String name) {
        List<Owner> owners = getHibernateTemplate().findByNamedQueryAndNamedParam("owner.get.by.name", "name", name);

        if (owners != null && owners.size() == 1) {
            return owners.get(0);
        }

        return null;
    }

    /**
     * Funkcja pobiera liste wszystkich wlascicieli bankomatow.
     * @return List<Owner>
     */
    public Set<Owner> getAll() {
        Set<Owner> owners = new HashSet<Owner>();
        List<Owner> tmp = null;

        Session session = this.getSession();
        if (session != null) {
            Criteria criteria = session.createCriteria(Owner.class);
            criteria.addOrder(Order.asc("name"));
            tmp = criteria.list();

            if (tmp != null) {
                for (Owner owner : tmp) {
                    owners.add(owner);
                }
            }
        }

        return owners;
    }

    /**
     * Funkcja zapisuje liste wlascicieli do bazy danych.
     * @param owners List<Owner>
     */
    public void saveAll(List<Owner> owners) {
        getHibernateTemplate().saveOrUpdateAll(owners);
    }
}
